package com.yaodian100.ec.cobranding;

import java.util.LinkedHashMap;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;

import com.yaodian100.ec.order.entity.Orders;

public class Onlylady {
	private final static String olKey = "daaf950cc162fcdcdd13ad6b64f06105";
	private final static String olSource = "yaodian100";

	public String olLogin(String cookieStrEncode, String ip, String useAgent) {
		String result = "";

		// Cookie[] cookies = request.getCookies();

		Map<String, Object> olInfo = new LinkedHashMap<String, Object>();

		olInfo.put("ip", ip);
		olInfo.put("cookie", cookieStrEncode);

		JSON oljson = JSONSerializer.toJSON(olInfo);

		String jsonStr = oljson.toString();

		StringBuffer keyStr = new StringBuffer("malluservalidate");
		keyStr.append(jsonStr);
		keyStr.append(olSource);
		keyStr.append(System.currentTimeMillis() / 1000);
		keyStr.append(olKey);
		// $key = md5(“mall{$object}{$method}{$json}{$source}{$time}{$code}”);
		String key = DigestUtils.md5Hex(keyStr.toString());

		// *****使用httpclient 送出
		NameValuePair[] data = new NameValuePair[4];
		data[0] = new NameValuePair("json", jsonStr);
		data[1] = new NameValuePair("source", olSource);
		data[2] = new NameValuePair("time", String.valueOf(System.currentTimeMillis() / 1000));
		data[3] = new NameValuePair("key", key);

		System.out.println("json:" + jsonStr);
		System.out.println("source:" + olSource);
		System.out.println("time:" + String.valueOf(System.currentTimeMillis() / 1000));
		System.out.println("key:" + key);

		result = sendPost("http://api.onlylady.com/mall/user/validate", data, useAgent);

		return result;
	}

	public String olGetEmail(String cookieStrEncode, String ip, String useAgent) {
		String result = "";

		// Cookie[] cookies = request.getCookies();

		Map<String, Object> olInfo = new LinkedHashMap<String, Object>();

		olInfo.put("ip", ip);
		olInfo.put("cookie", cookieStrEncode);

		JSON oljson = JSONSerializer.toJSON(olInfo);

		String jsonStr = oljson.toString();

		StringBuffer keyStr = new StringBuffer("malluseremail");
		keyStr.append(jsonStr);
		keyStr.append(olSource);
		keyStr.append(System.currentTimeMillis() / 1000);
		keyStr.append(olKey);
		// $key = md5(“mall{$object}{$method}{$json}{$source}{$time}{$code}”);
		String key = DigestUtils.md5Hex(keyStr.toString());

		// *****使用httpclient 送出
		NameValuePair[] data = new NameValuePair[4];
		data[0] = new NameValuePair("json", jsonStr);
		data[1] = new NameValuePair("source", olSource);
		data[2] = new NameValuePair("time", String.valueOf(System.currentTimeMillis() / 1000));
		data[3] = new NameValuePair("key", key);

		System.out.println("json:" + jsonStr);
		System.out.println("source:" + olSource);
		System.out.println("time:" + String.valueOf(System.currentTimeMillis() / 1000));
		System.out.println("key:" + key);

		result = sendPost("http://api.onlylady.com/mall/user/email", data, useAgent);

		return result;
	}

	public String olCreateOrder(Orders order) {
		String result = "";
		String areaStr = "上海市,上海市,徐汇区";
		String addrStr = "虹梅路2007号1号楼3楼";

		Map<String, Object> olInfo = new LinkedHashMap<String, Object>();
		olInfo.put("username", order.getLoginId());
		olInfo.put("sn", order.getOrderId());
		olInfo.put("time", System.currentTimeMillis() / 1000);
		olInfo.put("count", order.getOrderProduct().size());
		olInfo.put("amount", order.getMustPay());
		olInfo.put("name", "耀点100");
		olInfo.put("phone", "2133674420");
		olInfo.put("mobile", "2133674420");
		olInfo.put("email", "onlylady@yaodian100.com");
		olInfo.put("area", areaStr);
		olInfo.put("address", addrStr);
		olInfo.put("shipping", "货运");
		olInfo.put("payment", "支付");
		olInfo.put("shipping_fee", new Float("0.0"));
		olInfo.put("pay_fee", new Float("0.0"));
		olInfo.put("other_fee", new Float("0.0"));
		olInfo.put("discount", new Float("0.0"));

		JSON oljson = JSONSerializer.toJSON(olInfo);
		String jsonStr = oljson.toString();

		StringBuffer keyStr = new StringBuffer("mallordercreate");
		keyStr.append(jsonStr);
		keyStr.append(olSource);
		keyStr.append(System.currentTimeMillis() / 1000);
		keyStr.append(olKey);
		// $key = md5(“mall{$object}{$method}{$json}{$source}{$time}{$code}”);
		String key = DigestUtils.md5Hex(keyStr.toString());
		// json=[json]&source=[source]&time=[time]&key=[key]

		// 建立NameValuePair陣列傳送的資料, 對照為 (名稱, 內容)
		NameValuePair[] data = new NameValuePair[4];
		data[0] = new NameValuePair("json", jsonStr);
		data[1] = new NameValuePair("source", olSource);
		data[2] = new NameValuePair("time", String.valueOf(System.currentTimeMillis() / 1000));
		data[3] = new NameValuePair("key", key);

		result = sendPost("http://api.onlylady.com/mall/order/create", data, "");

		return result;
	}

	public String olUpdateOrder(Orders order, String updateTp) {
		String result = "";

		Map<String, Object> olInfo = new LinkedHashMap<String, Object>();

		olInfo.put("sn", order.getOrderId());
		olInfo.put("status", updateTp);
		// olInfo.put("shipping_time", order.getOrderProduct().get(0).getLogisticSendDt().getTime() / 1000);
		// olInfo.put("pay_time", order.getPaymentDt().getTime() / 1000);

		JSON oljson = JSONSerializer.toJSON(olInfo);
		String jsonStr = oljson.toString();

		StringBuffer keyStr = new StringBuffer("mallorderupdate");
		keyStr.append(jsonStr);
		keyStr.append(olSource);
		keyStr.append(System.currentTimeMillis() / 1000);
		keyStr.append(olKey);
		// $key = md5(“mall{$object}{$method}{$json}{$source}{$time}{$code}”);
		String key = DigestUtils.md5Hex(keyStr.toString());
		// json=[json]&source=[source]&time=[time]&key=[key]
		// 建立NameValuePair陣列傳送的資料, 對照為 (名稱, 內容)
		NameValuePair[] data = new NameValuePair[4];
		data[0] = new NameValuePair("json", jsonStr);
		data[1] = new NameValuePair("source", olSource);
		data[2] = new NameValuePair("time", String.valueOf(System.currentTimeMillis() / 1000));
		data[3] = new NameValuePair("key", key);

		result = sendPost("http://api.onlylady.com/mall/order/update", data, "");

		return result;
	}

	public String olCancelOrder(Orders order) {
		return olUpdateOrder(order, "3");
	}

	public String olCompleteOrder(Orders order) {
		return olUpdateOrder(order, "1");
	}

	public String olReturnOrder(Orders order) {
		return olUpdateOrder(order, "2");
	}

	private String sendPost(String actionURL, NameValuePair[] data, String useAgent) {
		String result = "";
		String bAgent = "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2) Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2";
		HttpClient client = new HttpClient();

		// 建立PostMethod實體, 並指派網址
		PostMethod post = new PostMethod(actionURL);

		// 將NameValuePair陣列設置到請求內容中
		post.setRequestBody(data);

		try {
			// 沒設user-agent不會通過驗證
			if (StringUtils.isNotBlank(useAgent))
				post.setRequestHeader("User-Agent", useAgent);
			post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

			// 返回狀態值.
			int statusCode = client.executeMethod(post);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + post.getStatusLine());
			}
			;

			// 取得回傳資訊.
			byte[] responseBody = post.getResponseBody();

			// request.setAttribute("paramStr", new String(responseBody));
			result = new String(responseBody);

		} catch (HttpException httpexc) {
			System.err.println("Fatal protocol violation: " + httpexc.getMessage());
			httpexc.printStackTrace();
		} catch (Exception ioexc) {
			System.err.println("Fatal transport error: " + ioexc.getMessage());
			ioexc.printStackTrace();
		} finally {
			// ** 無論如何都必須釋放連接.
			post.releaseConnection();
		}
		return result;
	}
}
